package com.nbgroup.service;

import com.nbgroup.dao.RoleRepositoty;
import com.nbgroup.dao.RoleUserRepositoty;
import com.nbgroup.entity.Role;
import com.nbgroup.entity.RoleUser;
import com.nbgroup.utils.QueryUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by 18545 on 2019/7/10.
 */
@Service
public class RoleService {
    @Autowired
    private RoleRepositoty roleRepositoty;
    @Autowired
    private QueryUtil queryUtil;
    @Autowired
    private RoleUserRepositoty roleUserRepositoty;

    public Role findOne(Long id){
        return roleRepositoty.findOne(id);
    }

    public Page<Role> findByPage(Integer page, Integer pageSize) throws Exception {
        if (null == page || "".equals(page) || "0".equals(page)) {//排空，设置默认值
            page = 1;
        }
        if (null == pageSize || "".equals(pageSize) || "0".equals(pageSize)) {//排空，设置默认值
            pageSize = 10;
        }
//        final Sort sort = new Sort(Sort.Direction.DESC, "createtime");//使用jpa的排序工具,按照事件创建时间倒序
        PageRequest pageRequest = new PageRequest(--page, pageSize);//使用jpa的分页工具
        return roleRepositoty.findAll(new Specification<Role>() {
            @Override
            public Predicate toPredicate(Root<Role> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> predicates = new ArrayList();
                predicates.add(cb.equal(root.get("sts"), 1));//查询可用
                query.where(predicates.toArray(new Predicate[predicates.size()]));
                return null;
            }
        }, pageRequest);//进行分页
    }

    public int getUserSizeByRoleId(String roleId){
        String sql = "SELECT * FROM role_user u WHERE u.role_id ='"+roleId+"'";
        List<RoleUser> appraiseList = queryUtil.query(sql, RoleUser.class);
        int size = appraiseList.size();
        return size;
    }
    public Role findRoleByName(String username){
        Role user = roleRepositoty.findByNameAndSts(username,"1");
        return user;
    }
    public String save(Role role){
//        user.setCreatetime(TimeTools.getTimeSec());
        role.setSts("1");
        if(role.getName()!=null&&!role.getName().equals("")){
            try{
                Role userBySelect = this.findRoleByName(role.getName());
                //检查可用用户中角色名是否重复
                if(userBySelect==null||userBySelect.getId().equals("")){
                    //添加角色
                    roleRepositoty.save(role);
                }else{
                    return "添加失败，用户名重复！";
                }
            }catch (Exception e){
                e.printStackTrace();
                return "添加失败，请联系管理员！";
            }
        }else{
            return "数据错误，请填写正确数据！";
        }
        return "添加成功";
    }
    //修改
    public String update(Role user){

//        if(user.getUsername()!=null&&!user.getUsername().equals("")&&user.getPassword()!=null&&!user.getPassword().equals("")){
        try{
            Role olduser = roleRepositoty.findOne(user.getId());
            olduser.setName(user.getName());
//            olduser.setCreatetime(TimeTools.getTimeSec());
            olduser.setSts("1");
//                //检查可用用户中用户名是否重复
//                if(this.findUserByName(user.getUsername())==null||this.findUserByName(user.getUsername()).getId().equals(user.getId())){
            roleRepositoty.saveAndFlush(olduser);
//                }else{
//                    return "修改失败，用户名重复！";
//                }
        }catch (Exception e){
            e.printStackTrace();
            return "修改失败，请联系管理员！！！";
        }
//        }else{
//            return "数据错误，请填写正确数据！";
//        }
        return "修改成功";
    }

    //删除
    public String delete(String id){
        Role user = roleRepositoty.findOne(Long.parseLong(id));
        try {
            if(!user.getName().equals("admin")){
                user.setSts("0");
                roleRepositoty.saveAndFlush(user);
            }else{
                return "删除失败，不能删除admin！！！";
            }

        }catch (Exception e){
            return "删除失败，请联系管理员！！！";
        }
        return "删除成功！";
    }

    public Role getInfoById(String id){
        return roleRepositoty.findOne(Long.parseLong(id));
    }

    public RoleUser findRoleByUserId(String userId){
        RoleUser byUserId = roleUserRepositoty.findByUserId(Long.parseLong(userId));
        return byUserId;
    }
    public  List<Role> findRoleNotBy(Long roleId){
        String sql = "SELECT * FROM role WHERE id <> '"+roleId+"'";
        List<Role> appraiseList = queryUtil.query(sql, Role.class);
        return appraiseList;
    }
}
